<template>
  <el-form ref="form" :model="form" label-position="left" class="form-fill">
    <el-row>
      <el-col :span="span">
        <el-form-item :label="labels.noData + ':'" label-width="200px">
          <el-switch
            :disabled="disabled"
            v-model="form.noData"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66">
          </el-switch>
        </el-form-item>
      </el-col>
    </el-row>
    <template v-if="!form.noData">
      <!-- 此部分不一样 -->
      <slot></slot>
      <!---------------->
    </template>
    <template v-else>
      <el-row>
        <el-col :span="span">
          <el-form-item :label="labels.selfEvaluate + ':'" label-width="200px">
            <el-select :disabled="disabled" v-model="form.selfEvaluate" placeholder="请选择">
              <el-option v-for="item in noDataOptions" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </template>
    <el-row>
      <el-col :span="span">
        <el-form-item :label="labels.report + ':'" label-width="200px">
          <el-input type="textarea" :disabled="disabled" :rows="3" placeholder="请输入内容" v-model="form.indexReport">
          </el-input>
        </el-form-item>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="span">
        <el-form-item :label="labels.material + ':'" label-width="200px">
          <el-button :disabled="disabled" size="mini" type="primary" @click="addMaterial">{{
            !addFile ? "添加材料" : "取消添加"
          }}</el-button>
          <div class="file" @click="viewPDF(file)" v-for="(file, index) in showFileList" :key="index">
            <div class="file-left">
              <i class="el-icon-document"></i>
              <div class="file-name">{{ file.name }}</div>
            </div>
            <div class="operation">
              <i class="el-icon-circle-check" style="color: #67c23a"></i>
              <i class="el-icon-download" style="color: #409eff" @click.stop="download(file)"></i>
              <i
                v-if="!disabled"
                class="el-icon-close"
                style="color: #f56c6c"
                @click.stop="deleteFile(file.fileName, index)"></i>
            </div>
          </div>

          <el-upload
            v-if="addFile"
            :before-upload="beforeUpload"
            :before-remove="beforeRemove"
            drag
            :http-request="customRequest"
            action="">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传jpg、png、pdf和word文件，且文件大小不超过10M</div>
          </el-upload>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form-item style="text-align: center">
      <el-button type="primary" @click="handleModify">{{ disabled ? "填写" : "取消" }}</el-button>
      <el-button type="primary" plain @click="handleSubmit" v-if="!disabled">确认</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import { uploadFile, onlineFile, getIndexJSON, delFileByName } from "@/api/admin/file"
import { getIndex, setIndex, delFile } from "@/api/indexAll"
import { isEmpty } from "@/util/empty"
import { getOptions } from "@/util/level"
import { getObj } from "@/api/river"

export default {
  props: ["riverId", "indexName", "indexId", "customForm"],
  data() {
    return {
      labels: {
        score: "系统评分",
        material: "支撑材料",
        report: "申报说明",
        noData: "无数据填写",
        selfEvaluate: "自评",
      },
      form: {
        id: null,
        riverId: null,
        score: null,
        fillType: 0,
        year: null,
        indexReport: null,
        noData: null,
        selfEvaluate: null,
        fileList: null,
      },
      noDataOptions: [],
      formBak: {},
      formData: null,
      showFileList: [],
      fileList: [],
      fileOriginName: null,
      addFile: false,
      isExpert: false,
      disabled: true,
      riverData: null,
      span: 18,
      isUploadFailed: false,
    }
  },
  watch: {
    riverId(val) {
      this.resetForm()
      if (!isEmpty(val)) {
        this.setRiverData(val).then(() => {
          this.getIndex()
        })
      }
    },
  },
  created() {
    Promise.all([getIndexJSON(), this.setRiverData(this.riverId)]).then((res) => {
      let jsonData = res[0].data
      if (jsonData != null && this.riverData != null) {
        let size = jsonData[this.indexName.slice(0, -5) + "Index"][this.riverData.level].length
        this.noDataOptions = getOptions(size)
      }
    })
    this.getIndex()
  },
  methods: {
    setRiverData(riverId) {
      return new Promise((resolve) => {
        getObj(riverId).then((res) => {
          this.riverData = res.data.data
          resolve()
        })
      })
    },
    //获取指标填写信息
    getIndex() {
      this.changeLoading(true)
      getIndex(this.indexName, this.riverId, 0).then((res) => {
        let item = res.data.data
        if (item != null) {
          Object.keys(this.form).forEach((key) => {
            this.form[key] = item[key]
          })

          //设置父组件customForm
          Object.keys(this.customForm).forEach((key) => {
            this.customForm[key] = item[key]
          })

          this.showFileList = JSON.parse(this.form.fileList)
          if (this.showFileList == null) {
            this.showFileList = []
          }
        }
        this.changeLoading(false)
      })
    },
    //点击修改
    handleModify() {
      if (this.disabled) {
        this.disabled = false
        this.formBak = { ...this.form }
        this.$emit("setDisabled", false)
        this.$emit("setBakData", true, false)
      } else {
        this.disabled = true
        this.$emit("setDisabled", true)
        this.addFile = false
        this.fileList = []
        Object.keys(this.form).forEach((key) => {
          this.form[key] = this.formBak[key]
        })
        this.$emit("setBakData", false, false)
      }
    },
    //点击提交
    handleSubmit() {
      this.$confirm("确认提交?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //将父组件的customForm复制到本组件的form
        Object.keys(this.customForm).forEach((key) => {
          this.form[key] = this.customForm[key]
        })
        let list = this.showFileList.concat(this.fileList)
        this.form.fileList = JSON.stringify(list)
        this.form.riverId = this.riverId
        this.form.year = this.riverData.year
        setIndex(this.indexName, this.form, this.indexId).then((res) => {
          this.$message.success("提交成功")
          this.changeLoading(true)
          this.resetForm()
          this.getIndex()
          this.$emit("refreshIndexList")
        })
      })
    },
    //重置表单和相关参数
    resetForm() {
      Object.keys(this.form).forEach((key) => {
        this.form[key] = null
      })
      this.fileList = []
      this.showFileList = []
      this.addFile = false
      this.disabled = true
      this.$emit("setDisabled", true)
      this.form.fillType = 0

      //重置父组件customForm
      Object.keys(this.customForm).forEach((key) => {
        this.customForm[key] = null
      })
    },
    //点击添加材料
    addMaterial() {
      this.addFile = !this.addFile
    },
    //删除材料
    deleteFile(fileName, index) {
      this.$confirm("该操作将无法恢复，确认删除材料?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        delFile(this.indexName, this.form.id, fileName).then((res) => {
          if (res.data.data) {
            this.$message.success("材料删除成功")
            this.showFileList.splice(index, 1)
          }
        })
      })
    },
    //文件上传之前
    beforeUpload(file) {
      const isPDF = file.type === "application/pdf"
      const isWord =
        file.type === "application/vnd.openxmlformats-officedocument.wordprocessingml.document" ||
        file.type === "application/msword"
      const isJPGOrPNG = file.type === "image/jpeg" || file.type === "image/png"
      const isOk = isPDF || isWord || isJPGOrPNG
      if (!isOk) {
        this.$message.error("上传文件格式不符合!")
        this.isUploadFailed = true
        return false
      }
      const isLe10M = file.size / 1024 / 1024 <= 10
      if (isLe10M) {
        this.formData = new FormData()
        this.fileOriginName = file.name
        this.formData.append("file", file)
      } else {
        this.$message.error("上传文件大小超过10M!")
      }
      this.isUploadFailed = !(isOk && isLe10M)
      return isOk && isLe10M
    },
    //自定义上传请求
    customRequest() {
      this.changeLoading(true)
      uploadFile(this.formData).then((res) => {
        let item = res.data.data
        if (!isEmpty(item)) {
          this.fileList.push({
            name: this.fileOriginName,
            url: item.url,
            fileName: item.fileName,
          })
        }
        this.changeLoading(false)
      })
    },
    beforeRemove(file, fileList) {
      if (!this.isUploadFailed) {
        return new Promise((resolve, reject) => {
          this.$confirm(`确定移除 ${file.name}？`)
            .then(() => {
              for (let i = 0; i < fileList.length; i++) {
                if (fileList[i].uid == file.uid) {
                  delFileByName(this.fileList[i].fileName).then((res) => {
                    if (res.data.data) {
                      this.fileList.splice(i, 1)
                      resolve(true)
                    }
                  })
                  break
                }
              }
            })
            .catch(() => {
              reject(false)
            })
        })
      }
      this.isUploadFailed = false
      return true
    },
    //下载文件
    download(file) {
      this.downBlobFile(file.url, {}, file.name)
    },
    //查看PDF
    viewPDF(file) {
      let fileName = file.url.split("/").slice(-1)[0]
      let bucketName = file.url.split("/").slice(-2)[0]
      onlineFile(bucketName, fileName).then((res) => {
        window.open(res.data.data, "_blank")
      })
    },
    //显示加载中
    changeLoading(val) {
      this.$emit("changeLoading", val)
    },
  },
}
</script>

<style scoped>
/deep/ .el-upload {
  width: 100%;
}
/deep/ .el-upload .el-upload-dragger {
  width: 100%;
}
</style>

<style lang="scss" scoped>
.form-fill {
  border-radius: 4px;
  border: 1px solid #ebeef5;
  padding: 20px 20px 0 20px;

  .el-input-number--small {
    width: 100%;
  }
  .file:first-of-type {
    margin-top: 5px;
  }
  .file {
    display: flex;
    flex-direction: row;
    color: #606266;
    align-items: center;
    justify-content: space-between;
    transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
    border-radius: 4px;
    padding: 0 5px;
    .file-name {
      transition: all 0.5s cubic-bezier(0.55, 0, 0.1, 1);
      margin-left: 5px;
    }
    .file-left {
      display: flex;
      flex-direction: row;
      align-items: center;
    }
    .operation {
      display: flex;
      flex-direction: row;
      align-items: center;
      .el-icon-download {
        display: none;
        margin-right: 5px;
      }
      .el-icon-close {
        display: none;
      }
    }
  }
  .file:hover {
    cursor: pointer;
    .file-name {
      color: #409eff;
    }
    .el-icon-close {
      display: block;
    }
    .el-icon-circle-check {
      display: none;
    }
    .el-icon-download {
      display: block;
    }
    background-color: #f5f7fa;
  }
}
</style>
